package Proj_pack;
import java.io.File;
import java.util.concurrent.CountDownLatch;


public class netz2135 {
	// static List<Knoten> alleKnoten;
	static SwitchingQueue unstable = new SwitchingQueue();
	static Maschen maschen;
	static int res;
	static CountDownLatch resultWait; 
	static CountDownLatch graphWait;
	static CountDownLatch edgeWait;
	static CountDownLatch switchWait;
	static CountDownLatch nextGenWait;
	static Thread queueSwitcher;
	static int many;
	
	public netz2135() {
		unstable = new SwitchingQueue();
		res = 0;
	}
	// test main
	public static void main(String[] argv){
		//		many = 100;												// kann benutzt werden wenn untere zeile auskommentiert
		many = Runtime.getRuntime().availableProcessors()+1;
		final Graph gr= new Graph();
		edgeWait = new CountDownLatch(argv.length);						//damit Parser aufeinander warten
		graphWait= new CountDownLatch(argv.length);						//damit main auf den(die) parser wartet
		resultWait = new CountDownLatch(many);   					
		switchWait= new CountDownLatch(many);
		nextGenWait= new CountDownLatch(1);

		
		for (int i = 0; i < argv.length; i++) {
			final File file=new File(argv[i]);	
			(new Thread(new Runnable(){
				public void run() {
					new xml2graph_parser(gr).createGraph(file);
					graphWait.countDown();
				};
			})).start();
		}
		boolean b1=false; do{	b1=false;
			try {graphWait.await();}catch(InterruptedException e1){b1=true;}
		}while(b1);
		maschen = new Maschen( gr);
		//  System.out.println(maschen);
		unstable.addAll(maschen.getMaschen());
		queueSwitcher = new Thread(new Runnable(){
			@Override
			public void run() {
				while(!Thread.currentThread().isInterrupted()){
					boolean b=false; do{	b=false;
					try {netz2135.switchWait.await();}catch(InterruptedException e1){b=true;}
					}while(b);
					unstable.switchQueue();
					netz2135.nextGenWait.countDown();
				}
//				System.err.println("switcher peace n' out!");
			}
			
		});
		queueSwitcher.start();
		
		for(int i = 0; i < many; i++){
			new Thread(new Worker()).start();
		}
		boolean b2=false; do{ 	b2=false;
			try {resultWait.await();}catch(InterruptedException e1){b2=true;}
		}while(b2);

		//  System.err.println("maschen: " + maschen);
		res=maschen.getMaschen().size();
		//		System.out.println("threads: "+ many + " Anzahl Stromnetze: " + res);
//		System.exit(res);				//TODO muss fuer JUnit-test auskommentiert werden, ABER fuer jar-file muss es drin sein!!!

	} 

	public int getRes(){
		return res;
	}


	public Maschen getMaschen(){
		return maschen;
	}
}